<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/1/4
 * Time: 15:42
 */
namespace App\Admin\Controllers;

use App\Http\Controllers\Controller;
use App\Models\AreaOrder;
use App\Models\Account\BehaviorTicketTotal;
use App\Models\PlayerForm;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Layout\Content;
use Encore\Admin\Grid;
use Illuminate\Http\Request;
use \Illuminate\Support\Facades\Input;
use App\Admin\Extra\Search\Html;

class AreaOrderController extends Controller{

    public function anyListAccount()
    {
        $req_param = Input::all();
        //OrderForm::getAccountByName();
        return Admin::content(function (Content $content)use($req_param) {

            $content->header('area order');
            $content->description('订单列表--根据服务器统计');
            $area = Input::get('cp_area');
            $area_data = \App\Models\Area::areaSelectData(0);

            $period_7 = \App\Service\Common::GetSomeDayPeriod(7, time());
            $param_7_day_arr_all = ['charge_ok' => 1, 'created_time' => ['start' => \App\Service\Common::GTF($period_7[0])]]; 
            $period_3 = \App\Service\Common::GetSomeDayPeriod(3, time());
            $param_3_day_arr_all = ['charge_ok' => 1, 'created_time' => ['start' => \App\Service\Common::GTF($period_3[0])]];
            $param_1_day_arr = ['charge_ok' => 1, 'created_time' => ['start' => date("Y-m-d", time() ) ]];
            $param_2_day_arr = ['charge_ok' => 1, 'created_time' => ['start' => date("Y-m-d", strtotime('-1 day') ), 'end'=> date("Y-m-d", strtotime('-0 day') ) ] ];
            $param_3_day_arr = ['charge_ok' => 1, 'created_time' => ['start' => date("Y-m-d", strtotime('-2 day') ), 'end'=> date("Y-m-d", strtotime('-1 day') ) ]];
            $param_4_day_arr = ['charge_ok' => 1, 'created_time' => ['start' => date("Y-m-d", strtotime('-3 day') ), 'end'=> date("Y-m-d", strtotime('-2 day') ) ]];
            $param_5_day_arr = ['charge_ok' => 1, 'created_time' => ['start' => date("Y-m-d", strtotime('-4 day') ), 'end'=> date("Y-m-d", strtotime('-3 day') ) ]];

            $content->row(Html::append([
                Html::input('OrderSerial', 'OrderSerial', \App\Service\Common::build_url_query(url()->current(),  ['cp_area' => $area])),
                Html::input('CooperatorOrderSerial', 'CooperatorOrderSerial', \App\Service\Common::build_url_query(url()->current(),  ['cp_area' => $area])),
                Html::button('GO', url()->current(), 'search-filter'),
                Input::get('charge_ok', 1) ? Html::button('Charge OK', \App\Service\Common::build_url_query(url()->current(), ['charge_ok' => 0]), 'btn-goto btn-info')
                : Html::button('Precharge', \App\Service\Common::build_url_query(url()->current(),  ['charge_ok' => 1]), 'btn-goto btn-warning'),

                Html::button('Today', \App\Service\Common::build_url_query(url()->current(),  $param_1_day_arr), 'btn-goto btn-warning'),
                Html::button('Day 2', \App\Service\Common::build_url_query(url()->current(),  $param_2_day_arr), 'btn-goto btn-warning'),
                Html::button('Day 3', \App\Service\Common::build_url_query(url()->current(),  $param_3_day_arr), 'btn-goto btn-warning'),
                Html::button('Day 4', \App\Service\Common::build_url_query(url()->current(),  $param_4_day_arr), 'btn-goto btn-warning'),
                Html::button('Day 5', \App\Service\Common::build_url_query(url()->current(),  $param_5_day_arr), 'btn-goto btn-warning'),

                Html::button('All 3 Days ', \App\Service\Common::build_url_query(url()->current(),  $param_3_day_arr_all), 'btn-goto btn-default'),
                Html::button('All 7 Days ', \App\Service\Common::build_url_query(url()->current(),  $param_7_day_arr_all), 'btn-goto btn-default'),
                Html::sjs(\App\Service\Common::build_url_query(url()->current(),  ['cp_area' => $area]))
            ]));
            
            $cond_q = $req_param;
            $cond_q['cp_area'] = 0;
            \Log::debug('area order list', [url()->current(), $cond_q]);
            $content->row(Html::append([
                '<span class="label label-success">'. $area_data[$area] .'('.$area.')</span>',
                Html::button('All Server', \App\Service\Common::build_url_query(url()->current(),  $cond_q), 'btn-goto btn-warning'),
            ]));


            $grid = Admin::grid(AreaOrder::class, function(Grid $grid) use ($area_data){
                
                $grid->model()->where('deleted_at', 0);
                $grid->actions(function($actions){
                    $actions->disableDelete();
                    $actions->disableEdit();
                   $actions->append('<a href="'.url('admin/areaorder/detail?CooperatorOrderSerial='). $actions->row->CooperatorOrderSerial .'"><i class="glyphicon glyphicon-eye-open"></i></a>');
                });
			    // $grid->id('ID')->sortable();
                // $grid->model()->orderBy('id', 'DESC');
                // 第一列显示id字段，并将这一列设置为可排序列
                // $grid->OrderSerial('OrderSerial');

                // 第二列显示title字段，由于title字段名和Grid对象的title方法冲突，所以用Grid的column()方法代替
                $grid->column('CooperatorOrderSerial');
                $grid->updated_at('updated-cur-time');
                // $grid->column('MerchandiseName');
                $grid->column('cp_product_id');
                
                $grid->column('prop_name');
                $grid->game_rmb('Game RMB')->display(function($value){
                    return "￥". $value ;
                });
                // $grid->cp_rmb('Deal Coin')->display(function($value){
                //     return '$'. $value ;
                // });
                $grid->game_lyto('Deal Coin')->display(function($value){
                    return '$'. $value ;
                });               
                // $grid->column('StartDateTime');
                // $grid->column('BankDateTime');
                // $grid->column('StatusMsg');
                // $grid->column('VoucherMoney');
                $grid->column('cp_area');
                // $grid->column('cp_extra');
                
                $grid->column('cp_player_id');
                $grid->cp_account('account')->display(function($value) {
                    return '<a href="'.url('admin/player/show?accountId='). $value .'">'.$value.'</a>';
                });
                $grid->device('Device');
                $grid->account_time('AccountTime');
                // $grid->column('created_at');
                // $grid->column('timestamp');
                // $grid->column('created_time');

                $grid->filter(function ($filter) use ($area_data){

                    $filter->between('created_time', 'Created Time')->datetime();
                    $filter->like('OrderSerial', 'OrderSerial')->placeholder('');
                    $filter->like('CooperatorOrderSerial', 'CooperatorOrderSerial')->placeholder('');
                    $filter->like('cp_player_id', 'Cp Player Id')->placeholder('');
                    $filter->like('cp_account', 'Cp Account')->placeholder('');
                    $filter->equal('cp_area', 'Area')->select($area_data);
                    $filter->equal('OrderStatus', 'OrderStatus')->select(\App\Models\AreaOrder::$order_status);
                });

                $excel = new \App\Admin\Extensions\CustomExporter("area_order.".time(), AreaOrder::getCustomExportHead(), null);
                $excel->setResouceFunc( function() {
                    return AreaOrder::getCustomExportData();
                } );
                
                $grid->exporter($excel);
            });
            $content->row($grid->render());
        });


    }

    // 删除列表
    public function anyListAccountDeleted() {
        Input::merge(['deleted_at' => 1]);
        return $this->anyListAccount();
    }

    // 订单详情
    public function anyOrderDetail()
    {
        $req_param = Input::all();

        return Admin::content(function (Content $content)use($req_param) {
            $one = AreaOrder::find($req_param['CooperatorOrderSerial']) ?: new AreaOrder();

            $content->header('Order Detail');
            $content->row(Html::append([
                Html::input('OrderSerial', 'OrderSerial', \App\Service\Common::build_url_query(url()->current(),  ['CooperatorOrderSerial' => $one->CooperatorOrderSerial])),
                Html::button('Repair Order', url('admin/areaorder/repair?CooperatorOrderSerial='.$req_param['CooperatorOrderSerial']), 'search-filter'),
                Html::sjs( \App\Service\Common::build_url_query(url('admin/areaorder/repair'),  ['CooperatorOrderSerial' => $one->CooperatorOrderSerial]))
            ] ));

            $data = [];
            $render = [];
            foreach ($one as $attr => $val) {
                $data[$attr] = $val;
            }
            $render['data'] = $data;
            $content->row(view('admin.orderform.order_detail', $render?:[]));

            $content->row(Html::append([
                Html::button('Soft Delete Order', url('admin/areaorder/delete-soft?CooperatorOrderSerial='.$one->CooperatorOrderSerial), 'confirm-ajax btn-danger'),
            ] ));
        });
    }

    public function anyRepairOrder()
    {
        $req_param = Input::all();
        $one = AreaOrder::find($req_param['CooperatorOrderSerial']) ?: new AreaOrder();

        // 订单已经支付，或者 订单不存在则不能 补发
        // if ($one->OrderSerial || !$one->CooperatorOrderSerial ) {
        //     echo json_encode(['code' => 444, 'msg' => admin_toastr('Order had repaired! or Error param','error'), 'data' => []]);
        //     return ;
        // }
        $one->OrderSerial = $req_param['OrderSerial'];

        // 修改 预支付订单的， 平台订单号
        AreaOrder::RepairOrder($one, $req_param['OrderSerial']);

        AreaOrder::sendRepairMsg($one, $data);
        \Log::debug('area order repair:', [$req_param['CooperatorOrderSerial'], $one->OrderSerial, $one->cp_player_id, $one->cp_area]);
        echo json_encode(['code' => 0,'status'=>true, 'msg' => admin_toastr('repair order successed','success!'), 'data' =>$one->OrderSerial]);
    }

    // 软删除
    public function anyDeleteOrder()
    {
        $req_param = Input::all();
        $one = AreaOrder::find($req_param['CooperatorOrderSerial']) ?: new AreaOrder();    
        AreaOrder::deleteSoft($req_param['CooperatorOrderSerial']);
        echo json_encode(['code' => 0,'status'=>true, 'msg' => admin_toastr('repair order successed','success!'), 'data' =>$one->OrderSerial]);  
    }

    public function anyTicketTotal() {
        $req_param = Input::all();
        //OrderForm::getAccountByName();
        return Admin::content(function (Content $content)use($req_param) {

            $content->header('Area Ticket');
            $content->description('红钻统计列表');
            $area = Input::get('cp_area')?:Input::get('area');
            $area_data = \App\Models\Area::areaSelectData(0);

            $period_7 = \App\Service\Common::GetSomeDayPeriod(7, time());
            $param_7_day_arr_all = ['charge_ok' => 1, 'op_time' => ['start' => \App\Service\Common::GTF($period_7[0])]]; 
            $period_3 = \App\Service\Common::GetSomeDayPeriod(3, time());
            $param_3_day_arr_all = ['charge_ok' => 1, 'op_time' => ['start' => \App\Service\Common::GTF($period_3[0])]];
            $param_1_day_arr = ['charge_ok' => 1, 'op_time' => ['start' => date("Y-m-d", time() ) ]];
            $param_2_day_arr = ['charge_ok' => 1, 'op_time' => ['start' => date("Y-m-d", strtotime('-1 day') ), 'end'=> date("Y-m-d", strtotime('-0 day') ) ] ];
            $param_3_day_arr = ['charge_ok' => 1, 'op_time' => ['start' => date("Y-m-d", strtotime('-2 day') ), 'end'=> date("Y-m-d", strtotime('-1 day') ) ]];
            $param_4_day_arr = ['charge_ok' => 1, 'op_time' => ['start' => date("Y-m-d", strtotime('-3 day') ), 'end'=> date("Y-m-d", strtotime('-2 day') ) ]];
            $param_5_day_arr = ['charge_ok' => 1, 'op_time' => ['start' => date("Y-m-d", strtotime('-4 day') ), 'end'=> date("Y-m-d", strtotime('-3 day') ) ]];

            $content->row(Html::append([
                Html::input('OrderSerial', 'OrderSerial', \App\Service\Common::build_url_query(url()->current(),  ['cp_area' => $area])),
                Html::input('CooperatorOrderSerial', 'CooperatorOrderSerial', \App\Service\Common::build_url_query(url()->current(),  ['cp_area' => $area])),
                Html::button('GO', url()->current(), 'search-filter'),
                Input::get('charge_ok', 1) ? Html::button('Charge OK', \App\Service\Common::build_url_query(url()->current(), ['charge_ok' => 0]), 'btn-goto btn-info')
                : Html::button('Precharge', \App\Service\Common::build_url_query(url()->current(),  ['charge_ok' => 1]), 'btn-goto btn-warning'),

                Html::button('Today', \App\Service\Common::build_url_query(url()->current(),  $param_1_day_arr), 'btn-goto btn-warning'),
                Html::button('Day 2', \App\Service\Common::build_url_query(url()->current(),  $param_2_day_arr), 'btn-goto btn-warning'),
                Html::button('Day 3', \App\Service\Common::build_url_query(url()->current(),  $param_3_day_arr), 'btn-goto btn-warning'),
                Html::button('Day 4', \App\Service\Common::build_url_query(url()->current(),  $param_4_day_arr), 'btn-goto btn-warning'),
                Html::button('Day 5', \App\Service\Common::build_url_query(url()->current(),  $param_5_day_arr), 'btn-goto btn-warning'),

                Html::button('All 3 Days ', \App\Service\Common::build_url_query(url()->current(),  $param_3_day_arr_all), 'btn-goto btn-default'),
                Html::button('All 7 Days ', \App\Service\Common::build_url_query(url()->current(),  $param_7_day_arr_all), 'btn-goto btn-default'),
                Html::sjs(\App\Service\Common::build_url_query(url()->current(),  ['cp_area' => $area]))
            ]));
            
            $cond_q = $req_param;
            $cond_q['area'] = $area;
            \Log::debug('area order list', [url()->current(), $cond_q]);
            $content->row(Html::append([
                '<span class="label label-success">'. $area_data[$area] .'('.$area.')</span>',
                Html::button('All Server', \App\Service\Common::build_url_query(url()->current(),  $cond_q), 'btn-goto btn-warning'),
            ]));


            $grid = Admin::grid(BehaviorTicketTotal::class, function(Grid $grid) use ($area_data, $cond_q){
                
                $grid->model()->where('deleted_at', 0);
                $grid->actions(function($actions){
                    $actions->disableDelete();
                    $actions->disableEdit();
                   $actions->append('<a href="'.url('admin/areaorder/detail?CooperatorOrderSerial='). $actions->row->CooperatorOrderSerial .'"><i class="glyphicon glyphicon-eye-open"></i></a>');
                });
			    // $grid->id('ID')->sortable();
                // $grid->model()->orderBy('id', 'DESC');
                // 第一列显示id字段，并将这一列设置为可排序列
                // $grid->OrderSerial('OrderSerial');

                // 第二列显示title字段，由于title字段名和Grid对象的title方法冲突，所以用Grid的column()方法代替
                $grid->op_module('Activity');
                $grid->op_m_alias('红钻活动')->display(function($value) {
                    return $value;
                });
                $grid->times('total')->display(function($value)use($cond_q){
                    $cond_q['ops'] = ['S.TICKET_REDUCE'];
                    $cond_q['op_module'] = [$this->op_module];
                    return '<a href="'.\App\Service\Common::build_url_query('/admin/behavior/behavior-coin',  $cond_q).'">'.$value.'</a>';
                });
                // $grid->column('MerchandiseName');


                $grid->filter(function ($filter) use ($area_data){

                    $filter->equal('cp_area', 'Area')->select(\App\Models\Area::areaSelectData(0));//
                    $filter->equal('vip', 'Vip');
                    $filter->equal('level', 'Level');
                    // $filter->in('ops', 'Operator')->multipleSelect(\App\Models\Account\Behavior::getOpAlias());
                    // $filter->in('op_module', 'Modules')->multipleSelect(\App\Models\Account\Behavior::getOpmoduleAlias());
                    $filter->between('op_time', 'Operator Time')->datetime();
                    // 或者在filter回调里面操作`$filter`实例
                });

            });
            $content->row($grid->render());
        });       
    }
}